import config from '@/config'

const responseStatusCallback = response => {
	uni.showToast({
		title: response.data.msg,
		icon: 'none',
		duration: 2000
	})
	return Promise.reject(response)
}

const service = (url, payload = {}, method = 'GET') => {

	const openid = uni.getStorageSync('openid')
	let header = {}
	// if (openid) header['Authorization'] = 'Bearer ' + token
	if (openid) payload.openid = openid
	// console.info(url, payload, method, `${config.api}/api${url}`)

	return new Promise((resolve, reject) => {
		uni.request({
			url: `${config.api}${url}`,
			method,
			data: payload,
			header,
			success: res => {
				// console.info('请求数据:' + JSON.stringify(res))
				if (res.statusCode == 200) {
					if (res.data.code !== 200) {
						if (res.data.code == 401) {
							uni.navigateTo({
								url: '/pages/login/login'
							})
							return resolve(res.data)
						}
						return responseStatusCallback(res)
					}

					return resolve(res.data)
				}
				return responseStatusCallback(res)
			},
			fail: res => {
				return responseStatusCallback(res)
			}
		})
	})

}

export default service